package com.qzsoft.zhjd.monitoring.modules.videogroup.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qzsoft.system.modules.zhjdsysdept.entity.ZhjdSysDeptEntity;
import com.qzsoft.system.modules.zhjdsysdept.service.ZhjdSysDeptService;
import com.qzsoft.zhjd.common.enums.BizCode;
import com.qzsoft.zhjd.common.utils.RenExceptionUtils;
import com.qzsoft.zhjd.monitoring.modules.videogroup.dto.VideoGroupTreeDto;
import com.qzsoft.zhjd.monitoring.modules.videogroup.entity.VideoGroupEntity;
import com.qzsoft.zhjd.monitoring.modules.videogroup.mapper.VideoGroupMapper;
import com.qzsoft.zhjd.monitoring.modules.videogroup.service.VideoGroupService;
import com.qzsoft.zhjd.monitoring.modules.videomonitor.entity.VideoMonitorEntity;
import com.qzsoft.zhjd.monitoring.modules.videomonitor.service.VideoMonitorService;

/**
 * @ClassName VideoGroupServiceImpl
 * @Description 视频分组业务接口实现
 * @author linhuawei
 * @since 2022-03-24
 */
@Service
public class VideoGroupServiceImpl extends ServiceImpl<VideoGroupMapper, VideoGroupEntity>
        implements VideoGroupService {

    @Autowired
    private ZhjdSysDeptService zhjdSysDeptService;

    @Autowired
    private VideoMonitorService videoMonitorService;

    private final String TOP_PID = "VG";

    @Override
    public List<VideoGroupTreeDto> tree() {
        // 获取基地列表
        Map<String, Object> params = new HashMap<String, Object>();
        List<ZhjdSysDeptEntity> baseList = zhjdSysDeptService.listForBase(params);

        // 如果基地列表存在，获取下属分组数据
        List<VideoGroupTreeDto> result = new ArrayList<VideoGroupTreeDto>();
        if (null == baseList || 0 == baseList.size()) {
            return result;
        }

        // 获取基地编号列表用于后续分组查询
        List<String> baseCodeList = new ArrayList<String>();
        for (ZhjdSysDeptEntity entity : baseList) {
            baseCodeList.add(entity.getCode());
        }

        // 获取分组列表
        QueryWrapper<VideoGroupEntity> queryWrapper = new QueryWrapper<VideoGroupEntity>();
        queryWrapper.in("base_code", baseCodeList);
        queryWrapper.orderByAsc("create_date");
        List<VideoGroupEntity> groupList = baseMapper.selectList(queryWrapper);

        // 获取视频列表
        QueryWrapper<VideoMonitorEntity> videoQueryWrapper = new QueryWrapper<VideoMonitorEntity>();
        videoQueryWrapper.in("base_code", baseCodeList);
        videoQueryWrapper.orderByAsc("base_code,name");
        List<VideoMonitorEntity> videoList = videoMonitorService.list(videoQueryWrapper);

        // 拼接树
        VideoGroupTreeDto dto;
        List<VideoGroupTreeDto> children;
        for (ZhjdSysDeptEntity entity : baseList) {
            dto = new VideoGroupTreeDto();
            dto.setId(entity.getId());
            dto.setCode(entity.getId());
            dto.setName(entity.getName());
            dto.setType("base");
            dto.setBaseCode(entity.getCode());
            children = coverToTree(entity.getCode(), TOP_PID, groupList, videoList);
            dto.setChildren(children);
            result.add(dto);
        }

        // 返回结果数据
        return result;
    }

    @Override
    public boolean save(VideoGroupEntity entity) {
        // 判断上级分组是否存在
        String pcode = TOP_PID;
        VideoGroupEntity temp;
        QueryWrapper<VideoGroupEntity> queryWrapper = null;
        if (null != entity.getPcode() && !TOP_PID.equals(entity.getPcode())) {
            pcode = entity.getPcode();
            queryWrapper = new QueryWrapper<VideoGroupEntity>();
            queryWrapper.eq("code", pcode);
            temp = baseMapper.selectOne(queryWrapper);
            if (null == temp) {
                RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "上级分组不存在");
            }
            entity.setBaseCode(temp.getBaseCode());
        }

        // 生成分组主键
        queryWrapper = new QueryWrapper<VideoGroupEntity>();
        queryWrapper.select(" max(code) as code ");
        queryWrapper.eq("pcode", pcode);
        temp = baseMapper.selectOne(queryWrapper);
        String code = null;
        if (null == temp) {
            code = pcode + "00";
        } else {
            String maxCode = temp.getCode();
            maxCode = maxCode.substring(maxCode.length() - 2, maxCode.length());
            int maxCodeNum = Integer.parseInt(maxCode, 36);
            if (maxCodeNum >= 1295) {
                RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "当前层级以达到最大数量");
            }
            maxCode = Integer.toString(maxCodeNum + 1, 36);
            if (1 == maxCode.length()) {
                maxCode = "0" + maxCode;
            }
            code = pcode + maxCode;
        }

        // 执行添加操作
        entity.setCode(code.toUpperCase());
        entity.setPcode(pcode.toUpperCase());
        return super.save(entity);
    }

    @Override
    public boolean removeById(Serializable id) {
        // 判断分组是否存在
        VideoGroupEntity group = baseMapper.selectById(id);
        if (null == group) {
            return true;
        }

        // 判断是否有下级分组，如果有不可删除
        QueryWrapper<VideoGroupEntity> groupQuery = new QueryWrapper<VideoGroupEntity>();
        groupQuery.likeRight("pcode", group.getCode());
        Integer count = baseMapper.selectCount(groupQuery);
        if (null != count && 0 < count) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "请先删除下级分组");
        }

        // 判断是否有下级摄像头，如果有不可删除
        QueryWrapper<VideoMonitorEntity> monitorQuery = new QueryWrapper<VideoMonitorEntity>();
        monitorQuery.likeRight("group_code", group.getCode());
        count = videoMonitorService.count(monitorQuery);
        if (null != count && 0 < count) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "请先删除下属摄像头");
        }

        // 删除视频分组
        return super.removeById(id);
    }

    /**
     * @Title coverToTree
     * @Description 视频分组转化为树状结构
     * @param baseCode  基地编号
     * @param pcode     上级分组主键
     * @param list      分组列表
     * @param videoList 视频列表
     * @return 树状结构
     */
    private List<VideoGroupTreeDto> coverToTree(String baseCode, String pcode, List<VideoGroupEntity> list,
            List<VideoMonitorEntity> videoList) {
        List<VideoGroupTreeDto> result = new ArrayList<VideoGroupTreeDto>();
        VideoGroupTreeDto dto;
        List<VideoGroupTreeDto> children;
        VideoGroupTreeDto videoDto;
        for (VideoGroupEntity entity : list) {
            if (baseCode.equals(entity.getBaseCode()) && pcode.equals(entity.getPcode())) {
                dto = new VideoGroupTreeDto();
                dto.setId(entity.getId());
                dto.setCode(entity.getCode());
                dto.setName(entity.getName());
                dto.setType("group");
                dto.setBaseCode(entity.getBaseCode());
                children = coverToTree(baseCode, entity.getCode(), list, videoList);
                for (VideoMonitorEntity video : videoList) {
                    if (entity.getCode().equals(video.getGroupCode())) {
                        videoDto = new VideoGroupTreeDto();
                        videoDto.setId(video.getId());
                        videoDto.setCode(video.getId());
                        videoDto.setName(video.getName());
                        videoDto.setType("video");
                        videoDto.setBaseCode(video.getBaseCode());
                        children.add(videoDto);
                    }
                }
                dto.setChildren(children);
                result.add(dto);
            }
        }
        return result;
    }

}
